package com.jxud.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.Map;

public class JwtUtils {
    private static String signingKey = "slyWebToken.#";
    private static Long expire = ChronoUnit.DAYS.getDuration().multipliedBy(50).toMillis(); //天
//    private static Long expire = ChronoUnit.MINUTES.getDuration().multipliedBy(1).toMillis();  //分钟

    /**
     * 生成JWT令牌
     * @param claims
     * @return
     */
    public static String generateJwt(Map<String, Object> claims) {
        String jwt = Jwts.builder()
                .addClaims(claims)
                .signWith(SignatureAlgorithm.HS256, signingKey)  // 签名算法，密钥
                .setExpiration(new Date(System.currentTimeMillis() + expire))   // 设置有效
                .compact();
        return jwt;
    }

    /**
     * 解析JWT令牌
     * @param jwt
     * @return
     */
    public static Claims parseJwt(String jwt) {
        Claims claims = Jwts.parser()
                .setSigningKey(signingKey)
                .parseClaimsJws(jwt)
                .getBody();
        return claims;
    }
}
